package com.xy.yunduo.web.cfg;

import com.xy.yunduo.web.filter.AccessLogFilter;
import com.xy.yunduo.web.filter.MessageLocaleFilter;
import com.xy.yunduo.web.filter.XssFilter;
import com.xy.yunduo.web.interceptor.DateParamInterceptor;
import com.xy.yunduo.web.interceptor.LoginInterceptor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class YunDuoMvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public LoginInterceptor loginInterceptor(){
        return new LoginInterceptor();
    }

//    @Bean
//    public DateParamInterceptor dateParamInterceptor(){
//        return new DateParamInterceptor();
//    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // addPathPatterns 用于添加拦截规则
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(loginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/api/account/login")
                .excludePathPatterns("/api/account/register")
                .excludePathPatterns("/api/account/logout");
//        registry.addInterceptor(dateParamInterceptor())
//                .addPathPatterns("/api/**");
        super.addInterceptors(registry);
    }

    @Bean
    public FilterRegistrationBean accessLogFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean(new AccessLogFilter());
        registration.addUrlPatterns("/*"); //
        registration.setName("logFilter");
        registration.setOrder(2);
        return registration;
    }
    @Bean
    public FilterRegistrationBean messageLocaleFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean(new MessageLocaleFilter());
        registration.addUrlPatterns("/*"); //
        registration.setName("messageLocaleFilter");
        registration.setOrder(1);
        return registration;
    }
    @Bean
    public FilterRegistrationBean xssFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean(new XssFilter());
        registration.addUrlPatterns("/api/*"); //
        registration.setName("xssFilter");
        registration.setOrder(4);
        return registration;
    }
}
